package com.tanhua.appserver.service;

import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.appserver.exception.BusinessException;
import com.tanhua.autoconfig.template.AipfaceTemplate;
import com.tanhua.autoconfig.template.OosTemplate;
import com.tanhua.dubbointerface.api.UserInfoApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.joda.time.LocalDate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    OosTemplate oosTemplate;
    @Autowired
    AipfaceTemplate aipfaceTemplate;

    public void save(UserInfo userInfo) {
        if (userInfo.getBirthday()!=null) {
            int birYear = Integer.parseInt(userInfo.getBirthday().split("-")[0]);
            int year = new LocalDate().getYear();
            userInfo.setAge(year-birYear);
            userInfoApi.save(userInfo);
        }
    }

    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        String url = oosTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        boolean detect = aipfaceTemplate.detect(url);
        if (!detect){
            throw new BusinessException(ErrorResult.faceError());
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setAvatar(url);
        userInfoApi.update(userInfo);
    }

    public UserInfoVo findUserInfoById(Long userId) {
        UserInfo userInfo =userInfoApi.findUserInfoById(userId);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,userInfoVo);
//        if (userInfo.getAge()!=null) {
//            userInfoVo.setAge(String.valueOf(userInfo.getAge()));
//        }
        return userInfoVo;
    }

    public void updateUserInfo(UserInfo userInfo) {
        int birYear = Integer.parseInt(userInfo.getBirthday().split("-")[0]);
        int year = new LocalDate().getYear();
        userInfo.setAge(year-birYear);
        userInfoApi.update(userInfo);
    }
}
